package com.ssy.lingxi.search.serviceImpl;

import com.ssy.lingxi.common.exception.BusinessException;
import com.ssy.lingxi.common.model.dto.UserLoginCacheDTO;
import com.ssy.lingxi.common.model.vo.PageVO;
import com.ssy.lingxi.common.response.ResponseCode;
import com.ssy.lingxi.search.api.model.request.channel.ChannelCommodityCollectBatchRequest;
import com.ssy.lingxi.search.api.model.request.channel.ChannelCommodityCollectRequest;
import com.ssy.lingxi.search.api.model.response.CollectResponse;
import com.ssy.lingxi.search.entity.Commodity;
import com.ssy.lingxi.search.entity.channel.CommodityCollectChannel;
import com.ssy.lingxi.search.repository.CommodityCollectChannelRepository;
import com.ssy.lingxi.search.repository.CommodityRepository;
import com.ssy.lingxi.search.service.ICommodityCollectChannelService;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 商品收藏实现类
 * @author jw.chen
 * @version 2.0.0
 * @date 2020/6/22
 */
@Service
public class CommodityCollectChannelServiceImpl implements ICommodityCollectChannelService {

    @Resource
    private CommodityCollectChannelRepository commodityCollectChannelRepository;

    @Resource
    private CommodityRepository commodityRepository;

    /**
     * 查询该商品是否已经收藏
     * @param channelCommodityId 渠道商品id
     */
    @Override
    public CollectResponse getCommodityCollect(Long channelMemberId, Long channelMemberRoleId, Long channelCommodityId, UserLoginCacheDTO sysUser, Long shopId) {
        CollectResponse collectResponse = new CollectResponse();
        Boolean exists = commodityCollectChannelRepository.existsByChannelCommodityIdAndMemberIdAndMemberRoleIdAndUserIdAndShopIdAndChannelMemberIdAndChannelMemberRoleId(channelCommodityId, sysUser.getMemberId(), sysUser.getMemberRoleId(), sysUser.getUserId(), shopId, channelMemberId, channelMemberRoleId);
        Integer count = commodityCollectChannelRepository.countByChannelCommodityIdAndShopId(channelCommodityId, shopId);
        collectResponse.setIsCollect(exists);
        collectResponse.setCount(count);
        return collectResponse;
    }

    /**
     * 查询商品收藏列表
     * @param pageVO
     */
    @Override
    public Page<CommodityCollectChannel> getCommodityCollectChannelList(UserLoginCacheDTO sysUser, Long shopId, Long channelMemberId, PageVO pageVO){
        Sort sort = Sort.by("createTime").descending();
        Pageable page = PageRequest.of(pageVO.getCurrent() - 1, pageVO.getPageSize(), sort);
        if(channelMemberId != null && channelMemberId > 0){
            return commodityCollectChannelRepository.findByMemberIdAndMemberRoleIdAndUserIdAndShopIdAndChannelMemberId(sysUser.getMemberId(), sysUser.getMemberRoleId(), sysUser.getUserId(), shopId, channelMemberId, page);
        }else{
            return commodityCollectChannelRepository.findByMemberIdAndMemberRoleIdAndUserIdAndShopId(sysUser.getMemberId(), sysUser.getMemberRoleId(), sysUser.getUserId(), shopId, page);
        }
    }

    /**
     * 查询商品收藏列表
     * @param pageVO
     */
    @Override
    public Page<CommodityCollectChannel> getCommodityCollectChannelList(UserLoginCacheDTO sysUser, PageVO pageVO){
        Sort sort = Sort.by("createTime").descending();
        Pageable page = PageRequest.of(pageVO.getCurrent() - 1, pageVO.getPageSize(), sort);
        return commodityCollectChannelRepository.findByMemberIdAndMemberRoleIdAndUserId(sysUser.getMemberId(), sysUser.getMemberRoleId(), sysUser.getUserId(), page);
    }

    /**
     * 添加商品收藏
     * @param commodityCollectChannelRequest
     * @return
     */
    @Override
    public Long saveCommodityCollectChannel(UserLoginCacheDTO sysUser, Long shopId, ChannelCommodityCollectRequest commodityCollectChannelRequest){
        Long channelMemberId = commodityCollectChannelRequest.getChannelMemberId();
        Long channelMemberRoleId = commodityCollectChannelRequest.getChannelMemberRoleId();
        Long channelCommodityId = commodityCollectChannelRequest.getChannelCommodityId();
        //检查该商品是否存在
        if(channelCommodityId != null && channelCommodityId > 0){
            //验证数据库中是否存在该数据
            List<Commodity> commodityList = commodityRepository.findByMemberListChannelCommodityId(channelCommodityId);
            if(commodityList == null || commodityList.size() <= 0){
                throw new BusinessException(ResponseCode.PRODUCT_COMMODITY_NOT_EXIST);
            }
        }else{
            throw new BusinessException(ResponseCode.PRODUCT_COMMODITY_NOT_EXIST);
        }
        //检查是否已经收藏过
        Boolean exists = commodityCollectChannelRepository.existsByChannelCommodityIdAndMemberIdAndMemberRoleIdAndUserIdAndShopIdAndChannelMemberIdAndChannelMemberRoleId(channelCommodityId, sysUser.getMemberId(), sysUser.getMemberRoleId(), sysUser.getUserId(), shopId, channelMemberId, channelMemberRoleId);
        if(exists){
            throw new BusinessException(ResponseCode.PRODUCT_COMMODITY_COLLECT_EXIST);
        }
        //数据库持久化对象
        CommodityCollectChannel commodityCollectChannel = new CommodityCollectChannel();
        commodityCollectChannel.setChannelMemberId(channelMemberId);
        commodityCollectChannel.setChannelMemberRoleId(channelMemberRoleId);
        commodityCollectChannel.setChannelCommodityId(channelCommodityId);
        commodityCollectChannel.setShopId(shopId);
        commodityCollectChannel.setMemberId(sysUser.getMemberId());
        commodityCollectChannel.setMemberName(sysUser.getCompany());
        commodityCollectChannel.setMemberRoleId(sysUser.getMemberRoleId());
        commodityCollectChannel.setMemberRoleName(sysUser.getMemberRoleName());
        commodityCollectChannel.setUserId(sysUser.getUserId());
        commodityCollectChannel.setUserName(sysUser.getUserName());
        commodityCollectChannel.setCreateTime(System.currentTimeMillis());
        commodityCollectChannelRepository.saveAndFlush(commodityCollectChannel);
        return commodityCollectChannel.getId();
    }

    /**
     * 批量添加商品收藏
     * @param channelCommodityCollectBatchRequest
     * @return
     */
    @Override
    public Boolean saveBatchCommodityCollect(UserLoginCacheDTO sysUser, Long shopId, ChannelCommodityCollectBatchRequest channelCommodityCollectBatchRequest) {
        Long channelMemberId = channelCommodityCollectBatchRequest.getChannelMemberId();
        Long channelMemberRoleId = channelCommodityCollectBatchRequest.getChannelMemberRoleId();
        List<Long> channelCommodityIdList = channelCommodityCollectBatchRequest.getChannelCommodityIdList();
        List<CommodityCollectChannel> resultList = channelCommodityIdList.stream().map(channelCommodityId -> {
            //检查该商品是否存在
            if (channelCommodityId != null && channelCommodityId > 0) {
                //验证数据库中是否存在该数据
                List<Commodity> commodityList = commodityRepository.findByMemberListChannelCommodityId(channelCommodityId);
                if(commodityList == null || commodityList.size() <= 0){
                    throw new BusinessException(ResponseCode.PRODUCT_COMMODITY_NOT_EXIST);
                }
            } else {
                throw new BusinessException(ResponseCode.PRODUCT_COMMODITY_NOT_EXIST);
            }
            //检查是否已经收藏过
            Boolean exists = commodityCollectChannelRepository.existsByChannelCommodityIdAndMemberIdAndMemberRoleIdAndUserIdAndShopIdAndChannelMemberIdAndChannelMemberRoleId(channelCommodityId, sysUser.getMemberId(), sysUser.getMemberRoleId(), sysUser.getUserId(), shopId, channelMemberId, channelMemberRoleId);
            if(!exists){
                //数据库持久化对象
                CommodityCollectChannel commodityCollectChannel = new CommodityCollectChannel();
                commodityCollectChannel.setChannelMemberId(channelMemberId);
                commodityCollectChannel.setChannelMemberRoleId(channelMemberRoleId);
                commodityCollectChannel.setChannelCommodityId(channelCommodityId);
                commodityCollectChannel.setShopId(shopId);
                commodityCollectChannel.setMemberId(sysUser.getMemberId());
                commodityCollectChannel.setMemberName(sysUser.getCompany());
                commodityCollectChannel.setMemberRoleId(sysUser.getMemberRoleId());
                commodityCollectChannel.setMemberRoleName(sysUser.getMemberRoleName());
                commodityCollectChannel.setUserId(sysUser.getUserId());
                commodityCollectChannel.setUserName(sysUser.getUserName());
                commodityCollectChannel.setCreateTime(System.currentTimeMillis());
                return commodityCollectChannel;
            }else{
                return null;
            }
        }).filter(Objects::nonNull).collect(Collectors.toList());
        if(resultList.size() > 0){
            commodityCollectChannelRepository.saveAll(resultList);
            return true;
        }else{
            return false;
        }
    }

    /**
     * 删除商品收藏
     * @param commodityCollectChannelRequest
     * @return
     */
    @Override
    public String deleteCommodityCollectChannel(UserLoginCacheDTO sysUser, Long shopId, ChannelCommodityCollectRequest commodityCollectChannelRequest) {
        Long channelCommodityId = commodityCollectChannelRequest.getChannelCommodityId();
        Long channelMemberId = commodityCollectChannelRequest.getChannelMemberId();
        Long channelMemberRoleId = commodityCollectChannelRequest.getChannelMemberRoleId();
        //验证数据库中是否存在该数据
        List<CommodityCollectChannel> commodityCollectChannelList = commodityCollectChannelRepository.findByChannelCommodityIdAndMemberIdAndMemberRoleIdAndUserIdAndShopIdAndChannelMemberIdAndChannelMemberRoleId(channelCommodityId, sysUser.getMemberId(), sysUser.getMemberRoleId(), sysUser.getUserId(), shopId, channelMemberId, channelMemberRoleId);
        if(commodityCollectChannelList != null && !commodityCollectChannelList.isEmpty()){
            commodityCollectChannelRepository.deleteAll(commodityCollectChannelList);
            return ResponseCode.SUCCESS.getMessage();
        }else{
            throw new BusinessException(ResponseCode.PRODUCT_COMMODITY_COLLECT_NOT_EXIST);
        }
    }

    /**
     * 删除商品收藏通过id
     * @param id
     * @return
     */
    @Override
    public String deleteCommodityCollectChannelById(UserLoginCacheDTO sysUser, Long id) {
        CommodityCollectChannel commodityCollectChannel = commodityCollectChannelRepository.findById(id).orElse(null);
        if(commodityCollectChannel != null){
            Long memberId = commodityCollectChannel.getMemberId();
            Long memberRoleId = commodityCollectChannel.getMemberRoleId();
            Long userId = commodityCollectChannel.getUserId();
            if(memberId.equals(sysUser.getMemberId()) && memberRoleId.equals(sysUser.getMemberRoleId()) && userId.equals(sysUser.getUserId())){
                commodityCollectChannelRepository.deleteById(id);
                return ResponseCode.SUCCESS.getMessage();
            }
        }
        throw new BusinessException(ResponseCode.PRODUCT_COMMODITY_COLLECT_NOT_EXIST);
    }

}

